package com.colorful.insuranceproject.claims;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.adapter.UploadRecordAdapter;
import com.colorful.insuranceproject.base.PLEActivity;
import com.colorful.insuranceproject.bean.UploadDetailsBean;
import com.colorful.insuranceproject.bean.UploadRecordBean;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.request.ClaimsRequest;
import com.lovely3x.common.activities.refresh.CanLoadMore;
import com.lovely3x.common.activities.refresh.CanRefresh;
import com.lovely3x.common.adapter.ListAdapter;
import com.lovely3x.common.utils.Response;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by handsome-Bob on 2017/8/18.
 * <p>
 * 上传记录  历史上传
 */
public class UploadRecordActivity extends PLEActivity implements CanLoadMore, CanRefresh, View.OnClickListener, ListAdapter.ViewClickedListener {

    private static final int GET_UPLOAD_RECORD_INFO_URL = 0X1;

    private static final int CANCEL_CLAIMS_URL = 0X2;

    private static final int GET_UPLOAD_DETAILS = 0X3;

    private ClaimsRequest claimsRequest;

    private UploadRecordAdapter uploadRecordAdapter;

    @Bind(R.id.lv_upload_record)
    ListView lvUploadRecord;

    @Bind(R.id.fl_fragment_list_empty_container)
    ViewGroup vgEmptyTipContainer;

    private int positions;

    @Override
    protected int getContentView() {
        return R.layout.activity_upload_record;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this);
        setTitle(getString(R.string.upload_record));
    }

    @Override
    protected void onViewInitialized() {
        uploadRecordAdapter = new UploadRecordAdapter(null, mActivity);
        lvUploadRecord.setAdapter(uploadRecordAdapter);
        claimsRequest = new ClaimsRequest(getHandler());
        uploadRecordAdapter.setOnViewClickedListener(this);
        handleLoadingContent();
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getPageData();
    }

    /**
     * 请求页面数据
     */
    private void getPageData() {
        if (claimsRequest != null) {
            claimsRequest.getUploadRecord(currentIndex, GET_UPLOAD_RECORD_INFO_URL);
        }
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            //  获取数据
            case GET_UPLOAD_RECORD_INFO_URL:
                handleRefreshState(response, uploadRecordAdapter);
                if (response.isSuccessful) {
                    if (currentIndex == 0 && ((List<UploadRecordBean>) response.obj).size() == 0) {
                        onContentStatusChanged(LOADING_FAILURE, getString(R.string.not_find_data), this);
                    } else {
                        setPageData((List<UploadRecordBean>) response.obj, response.addtional);
                        onContentStatusChanged(LOADING_SUCCESSFUL);
                    }
                } else {
                    if (response.addtional == DEFAULT_POST_FIRST_PAGE) {
                        onContentStatusChanged(LOADING_FAILURE, CodeTable.getInstance().getCodeDescription(response), this);
                    }
                }
                break;

            // 撤销理赔
            case CANCEL_CLAIMS_URL:
                dismissProgressCircle();
                if (response.isSuccessful) {
                    uploadRecordAdapter.getDatas().get(positions).setInsuranceStatus(4);
                    uploadRecordAdapter.notifyDataSetChanged();
                    showToast(getString(R.string.cancel_claims_success));
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;

            //  获取历史上传的理赔单的详情
            case GET_UPLOAD_DETAILS:
                if (response.isSuccessful) {
                    UploadDetailsBean ub = (UploadDetailsBean) response.obj;
                    int status = uploadRecordAdapter.getItem(positions).getInsuranceStatus();

                    Intent intentIndex = new Intent(this, ClaimsStepOneActivity.class);
                    Intent intentAdvertisement = new Intent(this, ClaimsStepTwoActivity.class);
                    Intent[] intents = new Intent[2];
                    intents[0] = intentIndex;
                    intentIndex.putExtra(ClaimsStepOneActivity.EXTRA_UPLOAD_BEAN, ub);
                    intentIndex.putExtra(ClaimsStepOneActivity.EXTRA_STATUS, status);
                    intents[1] = intentAdvertisement;
                    intentAdvertisement.putExtra(ClaimsStepTwoActivity.EXTRA_UPLOAD_BEAN, ub);
                    intentAdvertisement.putExtra(ClaimsStepTwoActivity.EXTRA_STATUS, status);
                    startActivities(intents);
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;
        }
    }

    private void setPageData(List<UploadRecordBean> obj, int index) {
        if (uploadRecordAdapter != null) {
            switch (index) {
                case DEFAULT_POST_FIRST_PAGE:
                    uploadRecordAdapter.setData(obj);
                    break;
                default:
                    uploadRecordAdapter.addDataToLast(obj);
                    break;
            }
        }
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    @Override
    public void onClick(View v) {
        handleLoadingContent();
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getPageData();
    }

    @Override
    protected ViewGroup getEmptyContainerView() {
        return vgEmptyTipContainer;
    }

    @Override
    public void onBeginRefresh() {
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        claimsRequest.getUploadRecord(currentIndex, GET_UPLOAD_RECORD_INFO_URL);

    }

    @Override
    public void onBeginLoadMore() {
        currentIndex++;
        claimsRequest.getUploadRecord(currentIndex, GET_UPLOAD_RECORD_INFO_URL);
    }

    @Override
    public void onViewClicked(int position, View view) {
        positions = position;
        UploadRecordBean bean = uploadRecordAdapter.getItem(position);
        switch (view.getId()) {
            case R.id.tv_operation_one://补充
                if (bean.getInsuranceStatus() == 1) {
                    claimsRequest.getUploadDetails(bean.getInsuranceId(), GET_UPLOAD_DETAILS);
                } else if (bean.getInsuranceStatus() == 3) {// 编辑
                    claimsRequest.getUploadDetails(bean.getInsuranceId(), GET_UPLOAD_DETAILS);
                }
                break;
            case R.id.tv_operation_two://撤销
                final String id = bean.getInsuranceId();
                new AlertDialog.Builder(mActivity)
                        .setTitle(getString(R.string.hint))
                        .setMessage(getString(R.string.confrim_revoke_upload))
                        .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showProgressCircle();
                                claimsRequest.cancelClaimsUrl(id, CANCEL_CLAIMS_URL);
                            }
                        }).setNegativeButton(getString(R.string.cancel), null).show();
                break;
            case R.id.tv_order_num:// 详情
                launchActivity(ClaimsDetailsActivity.class, ClaimsDetailsActivity.EXTRA_CLAIMS_ORDER_ID, bean.getInsuranceId());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            uploadRecordAdapter.getDatas().get(positions).setInsuranceStatus(1);
            uploadRecordAdapter.notifyDataSetChanged();
        }
    }
}
